package kr.hyunist.musicplayexer;

import java.util.ArrayList;

import kr.hyunist.musicplayexer.Adapter.ListAdapter;
import kr.hyunist.musicplayexer.Application.MediaApplication;
import kr.hyunist.musicplayexer.DTO.MyMusic;
import kr.hyunist.musicplayexer.Util.Util;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class CopyOfListMainActivity extends Activity {

	public static final String TAG = "MediaProject";
	final String SERVICE_ACTIVITY = "kr.hyunist.musicplayexer.MusicService";

	ArrayList<MyMusic> arList; // 음악들이 담겨있는 배열리스트
	ListView list; // 리스트뷰
	MyMusic music; // 음악의 정보
	ListAdapter adapter; // 커스텀 어댑터
	Intent intent = null; // playDetail을 띄우기 위한 인텐트 객체
	MediaApplication app; // application객체
	SeekBar mSeekProgress; // 진행시크바
	Handler mHandler; // 시크바 상태 변경 핸들러
	Runnable runnable; // 시크바 변경 스레드
	TextView nowTime; // 현재 재생 시간
	Intent sIntent;
	ImageView playIcon;
	
	// 현재 재생되는 음악란의 뷰
	ImageView nowAlbumImg;
	TextView nowTitle;
	TextView nowSinger;
	TextView nowPlayTime;
	ImageView playingIcon;
	Button nowPlayingbtn;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		startActivity(new Intent(CopyOfListMainActivity.this, IntroActivity.class));
		
		// 화면을 portrait(세로)화면으로 고정
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		// 어플리케이션 객체
		app = (MediaApplication) getApplication();

		// 어플리케이션 객체에 arList 등록
		arList = new ArrayList<MyMusic>();
		app.setArList(arList);

		adapter = new ListAdapter(this, app.getArList());
		list = (ListView) findViewById(R.id.list);
		list.setAdapter(adapter);

		sIntent = new Intent(SERVICE_ACTIVITY);
		bindService(sIntent, serviceCon, BIND_AUTO_CREATE);
		
		playingIcon = (ImageView) findViewById(R.id.playingicon);
		
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
			
				
				// 어플리케이션 객체에서 리스트 포지션을 전역으로 설정
				app.setCurrentPosition(position);
				
				Log.d(CopyOfListMainActivity.TAG, "메인액티비티에 app : " + app);
				Log.d(CopyOfListMainActivity.TAG, "메인액티비티에 app.mService : "
						+ app.mService);
				Log.d(CopyOfListMainActivity.TAG, "메인액티비티 음악 데이터 : "
						+ app.getArList().get(app.getCurrentPosition())
								.getData());


				try {

					// 음악 실행
					app.mService.onListItemSelectplayBackMusic(app.getCurrentPosition());
					
					//playingIcon.setVisibility(View.VISIBLE);
												
					Log.d(CopyOfListMainActivity.TAG, "mService객체 : " + app.mService);
					Log.d(CopyOfListMainActivity.TAG,
							"전역 position : " + app.getCurrentPosition());
					Log.d(CopyOfListMainActivity.TAG, "isPlaying의 상태는? : "
							+ app.mPlayer.isPlaying());
				} catch (Exception e) {

				}
								
				CurrentPositionPlayBack();
				//앱을 종료했다가 실행했을때 음악이 재생중이면 상태가 하단에 출력
				/*if(app.mPlayer != null){
					CurrentPositionPlayBack();
					mSeekProgress();
				} else {
					CurrentPositionPlayBack();
				}*/

			}

		});

		mSeekProgress();

	}

	private void mSeekProgress() {
		nowTime = (TextView) findViewById(R.id.nowTime);
		mSeekProgress = (SeekBar) findViewById(R.id.songprogress);
		mSeekProgress.setOnSeekBarChangeListener(mOnProgressSeek);	
		mHandler = new Handler();
		runnable = new Runnable() {

			@Override
			public void run() {
				mHandler.postDelayed(runnable, 200);
				try {
					if (app.mPlayer.isPlaying()) {
						//Log.d(ListMainActivity.TAG,"상세페이지의 app.mService.isPlaying() : " + app.mService.isPlaying());
						mSeekProgress.setMax(app.mService.getDuration());
						mSeekProgress.setProgress(app.mService.getCurrentPosition());
					}

					nowTime.setText(Util.milliSecToTime(String.valueOf(app.mService.getCurrentPosition())));
				} catch (Exception e) {
					
				}

			}
		};

		mHandler.postDelayed(runnable, 200);
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.d(CopyOfListMainActivity.TAG, "ListMainActivity onResume상태");
		CurrentPositionPlayBack();
	}

	// 하단 현재 재생 되는 음원 설정
	protected void CurrentPositionPlayBack() {
		// 음원에 대한 비트맵 이미지 변환
		Bitmap nowAlbumArt = Util.getArtworkQuick(CopyOfListMainActivity.this,
				Integer.parseInt((app.getArList().get(app.getCurrentPosition())
						.getAlbumID())), 120, 120);

		// 재생되는 음악 이미지
		nowAlbumImg = (ImageView) findViewById(R.id.nowalbumart);
		if (nowAlbumArt == null) {
			nowAlbumImg.setImageResource(R.drawable.noimage);
		} else {
			nowAlbumImg.setImageBitmap(nowAlbumArt);
		}

		// 현재 재생되고 있는 음악이미지비트맵을 클릭했을때 PlayDetail 액티비티를 띄움. 정보를 putExtra로
		// 전송
		nowAlbumImg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				intent = new Intent(getApplication(), PlayDetail.class);
				startActivity(intent);
			}

		});

		// 현재 재생 되는 음악의 정보를 하단에 출력
		nowTitle = (TextView) findViewById(R.id.nowtitle);
		nowTitle.setText(app.getArList().get(app.getCurrentPosition())
				.getMusicTitle());

		nowSinger = (TextView) findViewById(R.id.nowsinger);
		nowSinger.setText(app.getArList().get(app.getCurrentPosition())
				.getArtist());

		nowPlayTime = (TextView) findViewById(R.id.nowplayTime);
		nowPlayTime.setText(app.getArList().get(app.getCurrentPosition())
				.getPlayTime());

		nowPlayingbtn = (Button) findViewById(R.id.nowplaypauseicon);
		nowPlayingbtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
			}
			
		});
	}

	// 진행 시크바 이벤트 처리
	SeekBar.OnSeekBarChangeListener mOnProgressSeek = new OnSeekBarChangeListener() {

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
		}

		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			if (fromUser) {
				try {
					app.mService.seekTo(progress);
				} catch (RemoteException e) {

				}
			}
		}

	};

	ServiceConnection serviceCon = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			app.mService = IMediaService.Stub.asInterface(service);
			Log.d(CopyOfListMainActivity.TAG, "서비스 연결 성공했으면 이거 뜰꺼임!");
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			app.mService = null;
		}

	};

	BroadcastReceiver mStatusListener = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

		}

	};
	
	// 에러처리 토스트
	protected void ErrorToast(String str) {
		Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (app.mPlayer != null) {
			unbindService(serviceCon);
			serviceCon = null;
			app.mPlayer = null;
		}
	}

}
